import {
useState,
useEffect,
useRef
} from 'react'
export function useCachedSearch(url, param) {
const cache = useRef({});
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!param) {
setLoading(true)
setData([])
}
const fetchData = async () => {
if (cache.current[param]) {
const data = cache.current[param];
setData(data);
setLoading(false);
} else {
const response = await fetch(url);
const data = await response.json();
const newFilter = data.filter((value) => {
return value.stock_name.toLowerCase().includes(param.toLowerCase());
});
cache.current[param] = newFilter;
setData(newFilter);
setLoading(false);
}
};
if (param.length > 3)
fetchData();
}, [param]);
return {
data,
loading
};
};